package com.zhongwang.mms.module.jiaGongMaterial.service;

import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.*;
import com.zhongwang.mms.module.allocation.dao.AllocationOrderDao;
import com.zhongwang.mms.module.basic.dao.MMaterialsDao;
import com.zhongwang.mms.module.basic.model.MMaterialsModel;
import com.zhongwang.mms.module.basic.service.BoardService;
import com.zhongwang.mms.module.jiaGongMaterial.dao.MaterialInDao;
import com.zhongwang.mms.module.jiaGongMaterial.dao.MaterialStockDao;
import com.zhongwang.mms.module.jiaGongMaterial.model.*;
import com.zhongwang.mms.module.material.dao.*;
import com.zhongwang.mms.module.material.model.ComplexStorageModel;
import com.zhongwang.mms.module.material.model.CompositeOutcomeModel;
import com.zhongwang.mms.module.material.model.MOrderDetailModel;
import com.zhongwang.mms.module.material.model.MProCodeQueryModel;
import com.zhongwang.mms.module.material.service.MInventoryService;
import com.zhongwang.mms.module.overview.model.ProjectStatusModel;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.BigDecimalUtils;
import com.zhongwang.mms.util.ExportExcelUtils;
import com.zhongwang.mms.util.ShiroUtils;
import lombok.extern.log4j.Log4j2;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 原料库存查询 服务层
 * @Author: China.wsg
 * @Date: 2020/04/01 11:23
 */
@Log4j2
@Service
public class MaterialStockService {
    @Autowired
    private ComplexStorageDao complexStorageDao;

    @Value("${user.upload.path}")
    private String uploadPath;

    @Value("${spring.profiles.active}")
    private String active;
    @Autowired
    private LogService logService;
    @Autowired
    private MaterialStockDao materialStockDao;

    /**
     * 导出原料在库明细
     *
     * @param param            查询条件
     * @param matTypeIdList    类型Id多选
     * @param matQualityIdList 材质Id多选
     * @param matSpecIdList    规格Id多选
     * @return
     */
    public JsonResult exportExcel(JMaterialAllModel param, @RequestParam(value = "matTypeIdList[]", required = false) List<String> matTypeIdList,
                                  @RequestParam(value = "matQualityIdList[]", required = false) List<String> matQualityIdList,
                                  @RequestParam(value = "matSpecIdList[]", required = false) List<String> matSpecIdList,
                                  @RequestParam(value = "whiIdList[]", required = false) List<String> whiIdList) {
        JsonResult jsonResult = new JsonResult();
        //获取当前用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        logService.saveLog("甲供件-原料库库存综合查询——导出", "用户:【" + user.getName() + "】执行导出操作！");
        Subject userSubject = ShiroUtils.getSubject();
        //存储/读取Excel的文件夹的路径 mms文件夹下/用户账户/
        String path = uploadPath + user.getAccount() + "/";
        String excelFileName = "甲供件-原料库库存综合查询.xlsx";
        try {
            //1.创建临时内存表名
            String tempTableName = "##" + user.getAccount() + (UUID.randomUUID().toString().replace("-", ""));
            param.setTempTableName(tempTableName);
            //2.查询出数据导入到临时表
            CreateStorageTempTable(param, matTypeIdList, matQualityIdList, matSpecIdList, whiIdList, true);
            //3.导出Excel
            if (ExportExcelUtils.BuildExcel(path, excelFileName, tempTableName, active, true)) {
                jsonResult.setData(excelFileName);
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
            } else {
                jsonResult.setType(JsonResult.ResultType.ERROR);
            }
        } catch (Exception e) {
            log.debug(e.getMessage());
            e.printStackTrace();
            jsonResult.setType(JsonResult.ResultType.ERROR);
        }
        return jsonResult;
    }

    /**
     * 查询原料在库明细
     *
     * @param jMaterialAllModel 查询条件
     * @param matTypeIdList     类型Id多选
     * @param matQualityIdList  材质Id多选
     * @param matSpecIdList     规格Id多选
     * @return
     */
    public void CreateStorageTempTable(JMaterialAllModel jMaterialAllModel, List<String> matTypeIdList, List<String> matQualityIdList, List<String> matSpecIdList, List<String> whiIdList, Boolean IsHavSeeMoney) {

        StringBuilder sb;

        // 类型多选条件
        if (matTypeIdList != null && matTypeIdList.size() > 0) {
            sb = new StringBuilder();
            for (int i = 0; i < matTypeIdList.size(); i++) {
                sb.append(matTypeIdList.get(i)).append(",");
            }
            jMaterialAllModel.setMatTypeIdQueryList("'" + StringUtils.join(sb.toString().substring(0, sb.toString().length() - 1).split(","), "','") + "'");
        }
        // 材质多选条件
        if (matQualityIdList != null && matQualityIdList.size() > 0) {
            sb = new StringBuilder();
            for (int i = 0; i < matQualityIdList.size(); i++) {
                sb.append(matQualityIdList.get(i)).append(",");
            }
            jMaterialAllModel.setMatQualityIdQueryList("'" + StringUtils.join(sb.toString().substring(0, sb.toString().length() - 1).split(","), "','") + "'");
        }
        // 规格多选条件
        if (matSpecIdList != null && matSpecIdList.size() > 0) {
            sb = new StringBuilder();
            for (int i = 0; i < matSpecIdList.size(); i++) {
                sb.append(matSpecIdList.get(i)).append(",");
            }
            jMaterialAllModel.setMatSpecIdQueryList("'" + StringUtils.join(sb.toString().substring(0, sb.toString().length() - 1).split(","), "','") + "'");
        }
        if (whiIdList != null && whiIdList.size() > 0) {
            sb = new StringBuilder();
            for (int i = 0; i < whiIdList.size(); i++) {
                sb.append(whiIdList.get(i)).append(",");
            }
            jMaterialAllModel.setWhiIdQueryList("'" + StringUtils.join(sb.toString().substring(0, sb.toString().length() - 1).split(","), "','") + "'");
        }
        if (jMaterialAllModel.getWhiIdQueryList() != null && jMaterialAllModel.getWhiIdQueryList().equals("''")) {
            jMaterialAllModel.setWhiIdQueryList(null);
        }
        if (jMaterialAllModel.getWhiIdListStr() != null && jMaterialAllModel.getWhiIdListStr().equals("")) {
            jMaterialAllModel.setWhiIdListStr(null);
        }
        materialStockDao.createComplexStorageTempTable(jMaterialAllModel);
    }

    /**
     * 根据条件查询项目完成时间
     *
     * @param jMaterialAllModel 查询条件
     * @return list
     */
    public List<JMaterialAllModel> findOutcome(JMaterialAllModel jMaterialAllModel, List<String> whiIdList) {
        List<JMaterialAllModel> list = new ArrayList<>();
        try {
            StringBuilder sb;

            if (whiIdList != null && whiIdList.size() > 0) {
                sb = new StringBuilder();
                for (int i = 0; i < whiIdList.size(); i++) {
                    sb.append(whiIdList.get(i)).append(",");
                }
                jMaterialAllModel.setWhiIdQueryList("'" + StringUtils.join(sb.toString().substring(0, sb.toString().length() - 1).split(","), "','") + "'");
            }
            jMaterialAllModel.setOdaRedFlag(1);
            list = materialStockDao.findCompositeOutcome(jMaterialAllModel);
        } catch (Exception e) {
            log.error("甲供件-原料库出入库综合查询异常：" + e.getMessage());
        }
        return list;
    }

    /**
     * 列表 导出
     *
     * @param param 查询条件
     */
    public JsonResult exportExcel(JMaterialAllModel param) {
        JsonResult jsonResult = new JsonResult();
        StringBuilder sb;
        if (param.getWhiIdList() != null && param.getWhiIdList().size() > 0) {
            sb = new StringBuilder();
            for (int i = 0; i < param.getWhiIdList().size(); i++) {
                sb.append(param.getWhiIdList().get(i)).append(",");
            }
            param.setWhiIdQueryList("'" + StringUtils.join(sb.toString().substring(0, sb.toString().length() - 1).split(","), "','") + "'");
        }
        param.setOdaRedFlag(1); // 不显示红字
        //获取当前用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        logService.saveLog("甲供件-原料库出入库综合查询——导出", "用户:【" + user.getName() + "】执行导出操作！");
        //存储/读取Excel的文件夹的路径 mms文件夹下/用户账户/
        String path = uploadPath + user.getAccount() + "/";
        Subject userSubject = ShiroUtils.getSubject();
        String excelFileName = "甲供件-原料库出入库综合查询.xlsx";
        try {
            //1.创建临时内存表名
            String tempTableName = "##" + user.getAccount() + (UUID.randomUUID().toString().replace("-", ""));
            param.setTempTableName(tempTableName);
            //2.查询出数据导入到临时表

            materialStockDao.createMinQueryTempTableByParam(param);

            //3.导出Excel
            if (ExportExcelUtils.BuildExcel(path, excelFileName, tempTableName, active, true)) {
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setData(excelFileName);
            } else {
                jsonResult.setType(JsonResult.ResultType.ERROR);
            }
        } catch (Exception e) {
            log.debug(e.getMessage());
            e.printStackTrace();
            jsonResult.setType(JsonResult.ResultType.ERROR);
        }
        return jsonResult;
    }

    public List<JMaterialAllModel> findCompositeOutcome(JMaterialAllModel jMaterialAllModel) {
        return  materialStockDao.findCompositeOutcome(jMaterialAllModel);
    }
}
